<?php
// TODO: Modify
require "../utility.php";

function keepUnique(mysqli $conn, string $user_id, string $book_id): bool {
    $query_str = "SELECT * FROM Comments WHERE userID = $user_id AND bookID = $book_id;";
    $query = $conn->query($query_str);
    if ($query->fetch_row()) {
        $query->close();
        return false;
    } else {
        $query->close();
        return true;
    }
}

function addCommentToDatabase(mysqli $conn, string $user_id, string $book_id, string $content, string $score): bool {
    $insert_str = "INSERT INTO Comments (bookID, userID, content, score) VALUES(?, ?, ?, ?);";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("iisi", $book_id, $user_id, $content, $score);
    return $insert_stmt->execute();
}

$comment_json = getJsonDataFromRawInput();

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null &&
    check_keys($comment_json, "bookID", "content", "score")) {

    $book_id = $comment_json["bookID"];
    $content = $comment_json["content"];
    $score   = $comment_json["score"];
    if (addCommentToDatabase($conn, $user_id, $book_id, $content, $score)) {
        // success
        http_response_code(200);
    }
}

$conn->close();

?>
